<?php
/**
 * User类
 */
namespace app\index\controller;

use app\index\model\UserModel;
use app\index\model\SchoolModel;
use app\index\model\RedisModel;
// use app\index\util\Response;

/**
 * Undocumented class
 */
class User extends Base
{

    protected $model;
    /**
     * Undocumented function
     *
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        $this->model = new UserModel();
    }
    

    /**
     * 登录
     *
     * @return json 用户登录信息
     */
    public function login()
    {
        $redisModel = new RedisModel();
        $model = $this->model;
        $response = $this->response;
        $mobile = $this->param('mobile');
        $password = $this->param('password');
        
        $data = [
            'mobile' => $mobile,
            'password' => $password,
        ];
        $user = $model->getUserByMoblie($mobile);
        // echo $password;die;
        if (!$user) {
            $response->message = '用户名或密码错误';
            goto err;
        }
        if (!verifyPwd($password, $user['password'])) {
            $response->message = '用户名或密码错误';
            goto err;
        }
        
        $token = generateSessionToken();
        
        $redisVal = json_encode(
            [
                'mobile' => $mobile,
                'uid' => $user['uid'],
                'validtime' => time(),
            ]
        );
        
        if ($redisModel->redisSet('token:'.$token, $redisVal, 5 * 60) === false) {
            $response->message = '登录失败';
            goto err;
        }

        //获取登录信息
        // $user = $this->model->getUser($user['uid']);    

        unset($data['password']);
        $data['token'] = $token;
        $response->data = $data;
        return json($response->getData());
        err:
        $response->code = 100;
        return json($response->getData());
    }

    /**
     * 退出登录
     *
     * @return void
     */
    public function logout()
    {
        $response = $this->response;
        $redisModel = new RedisModel();
        $userModel = new UserModel();
        $user = $this->user;
        $userModel->logPush($user['uid']);
        $token = $this->header;
        if (isset($token['token'])) {
            $redisModel->redisDel($token['token']);
        }
        return json($response->getData());
    }

    /**
     * 注册
     *
     * @return json 用户注册信息
     */
    public function register()
    {
        $response = $this->response;
        $model = $this->model;
        $mobile = $this->param('mobile');
        $code = $this->param('code');
        $password = $this->param('password');
        $redisModel = new RedisModel();
        $data = [
            'mobile' => $mobile,
            'code' => $code,
            'password' => $password,
        ];
         //验证验证码
        if ($code == 999) {
            goto nex;
        }
        $data = $this->verifyCode($mobile, $code, 1);
        if ($data['code'] != 200) {
            return json($data);
        }
        nex:
        $checkUser = $model->getUserByMoblie($mobile);
        if (isset($checkUser)) {
            $response->message = '用户已注册';
            goto err;
        }
        
        //保存用户信息
        $data = [
            'mobile'  =>  $mobile,
            'password'  =>  hashPwd($password),
        ];
        $uid = $model->reg($data);
        if (false === $uid) {
            $response->message = '注册失败';
            goto err;
        }
        
        $token = generateSessionToken();
        $redisVal = json_encode(
            [
                'mobile' => $mobile,
                'uid' => $uid,
                'validtime' => time(),
            ]
        );
        if ($redisModel->redisSet('token:'.$token, $redisVal, 5 * 60) === false) {
            $response->message = '未知错误';
            goto err;
        }
        unset($data['password']);
        $data['token'] = $token;
        $response->data = $data;
        return json($response->getData());
        err: 
        $response->code = 100;
        return json($response->getData());

    }

    /**
     * 忘记密码
     *
     * @return json 用户忘记密码信息
     */
    public function forget()
    {
        $redisModel = new RedisModel();
        $response = $this->response;
        $mobile = $this->param('mobile');
        $newPwd = $this->param('new_password');
        $rePwd = $this->param('re_password');
        $code = $this->param('code');


        // $validate = new \app\index\validate\User;
  
        // if (!$validate->scene('forgotPwd')->check($data)) {
        //     $response->message = $validate->getError();
        //     goto err;
        // }
    
        $uid = $this->user['uid'];
        
        $base = $this->model->getUserByModel($mobile);
        if (!$base) {
            $response->message = '手机号未注册';
            goto err;
        }

        if($uid && $base['uid'] != $uid)
        {            
            $response->message = '信息错误';
            goto err;
        }
      
        $data = [
            'uid' => $base['uid'],
            'password' => $newPwd,
        ];

        $markcode = 999999;
        //验证验证码
        if ($code != $markcode) 
        {
            $response->message = '验证码错误';
            goto err;
        }

        $data['password'] = hashPwd($data['password']);
        //修改密码
        $user = $this->model->updateUserPwd($data);
        if($user===true)
        {
            $response->message = '修改成功';
        }
        else
        {
            $response->message = '修改失败';
        }
    
        return json($response->getData());
        err:
        $response->code = 100;
        return json($response->getData());
    }

    /**
     * 个人资料
     *
     * @return json
     */
    public function userInfo()
    {
        $user = $this->user;
        $response = $this->response;
        $data = $this->userDetail($user, $this->role);
        $response->data = $data;
        return json($response->getData());
    }

    /**
     * 用户信息
     *
     * @param string $user 用户
     * @param int    $role 用户角色
     * 
     * @return void
     */
    protected function userDetail($user, $role)
    {
        $purse = $this->model->purse($user['uid']);
        switch ($role) {
            case 1:
                $schoolModel = new SchoolModel();
                $school = $schoolModel->getSchool($user['school_id']);
                $grade = $schoolModel->getGrade($user['class_id']);
                $stu = [                
                    'stage' => $user['stage'],
                    'enter_time' => $user['enter_time'],
                    'score' => $purse['score'],
                    'school_id' => $user['school_id'],
                    'grade_id' => $grade['grade_id']??0,
                    'class_id' => $user['class_id']??0,
                    'school_name' => $school['school_name'] ?? '',
                    'grade_name' => $grade['grade_name'] ?? '',
                    'class_name' => $grade['class_name'] ?? '',
                ];
                break;

            case 2:
                $schoolModel = new SchoolModel();
                $school = $schoolModel->getSchool($user['school_id']);
                $teh = [
                    
                    'type' => $user['type'],
                    'school_id' => $user['school_id'],
                    'school_name' => $school['school_name'] ?? '',
                ];
                
                if($user['type'] == ($user['type'] | $this->teacher_classTeacher))
                {
                    // 推荐码
                    $teh['recommen_token'] = $user['recommen_token'];
                    
                    $teh['share_icon']=$this->share_icon;
                    $teh['share_url']=$this->share_advisor_login_url.$user['recommen_token'];
                    $teh['share_title']=$this->share_advisor_login_title;
                    $teh['share_content']=$this->share_advisor_login_content;
                }

                break;

            case 3:
            
                $city = $this->model->cityByCode($user['citycode']);
                $cityname = $city['name'];
                $mgr = 
                [
                    'cityname' => $cityname,
                ];
                break;

            case 4:
                
                $recommen_user = $this->model->getUser($user['recommen_uid']); #我的推荐人
                
                $advisor=
                [
                    'recommen_user' => $recommen_user['realname']??'',
                    'verify' => $user['verify'],
                    'refuse_reason' => $user['refuse_reason'],
                ];                
                break;
        }
        
        // $base = $this->model->baseUser($user['uid']);
        $type = 0;
        if(isset($user['type']))
        {
            $type= $user['type'];
        }

        $appMenu = $this->model->getAppMenu($role,$type);

        $data = [
            'uid' => $user['uid'],
            'role' => $role,
            'mobile' => $user['mobile'],
            'nickname' => $user['nickname'],
            'headimg' => $user['headimg'],
            'sex' => $user['sex'],
            'motto' => $user['motto'],
            'birth_day' => $user['birth_day'],
            'name' => $user['realname'], #name=>realname
            'has_new_msg' => $user['has_new_msg'],
            'stu' => $stu ?? ["a"=>""],
            'teh' => $teh ?? ["a"=>""],
            'mgr' => $mgr ?? ["a"=>""],
            'advistor' => $advisor ?? ['a'=>''],
            'appmenu'=>$appMenu ?? ["a"=>""],
        ];
        return $data;
    }

    /**
     * 修改个人资料
     *
     * @return json
     */
    public function revise()
    {
        $user = $this->user;
        $response = $this->response;
     
        $role = $this->role;
        $baseInfo = [];
        $info = [];
        if ($this->param('headimg') !== null) 
        {
            $baseInfo['headimg'] = $this->param('headimg');
            
        }
        if ($this->param('nickname') !== null) 
        {  
            if(testEmoji($this->param('nickname')) === 1)
            {
                $response->message = '输入内容不能有表情';
                goto err;
            }
            $baseInfo['nickname'] = $this->param('nickname');
        }
        if ($this->param('sex') !== null) 
        {
            $baseInfo['sex'] = $this->param('sex') == 1 ? 1 : 0;
        }
        if ($this->param('motto') !== null) 
        {
            if(testEmoji($this->param('motto')) === 1)
            {
                $response->message = '输入内容不能有表情';
                goto err;
            }
            $baseInfo['motto'] = $this->param('motto');
        }
        if ($this->param('birth_day')) 
        {
            $baseInfo['birth_day'] = $this->param('birth_day');
        }

        if ($this->param('name') !== null) {
            if(testEmoji($this->param('name')) === 1)
            {
                $response->message = '输入内容不能有表情';
                goto err;
            }
            $baseInfo['realname'] = $this->param('name');
        }

        switch ($role) {
            case $this->role_student:
                if ($this->param('enter_time')) {
                    $info['enter_time'] = $this->param('enter_time');
                }
                if ($this->param('school_id') !== null) {
                    $info['school_id'] = $this->param('school_id');
                }
                if ($this->param('class_id') !== null) {
                    $info['class_id'] = $this->param('class_id');
                    $schoolModel = new SchoolModel();
                    $schoolInfo = $schoolModel->getGrade($info['class_id']);
                    $info['stage'] = $schoolInfo['stage'];
                }
                break;
            case $this->role_teacher:
                break;
            case $this->role_zone:
                break;
            case $this->role_advisor:
                break;                
            default:
        }

        if (!$baseInfo && !$info) {
            goto success;
        }
        else
        {
            $ex ;
            if (false === $this->model->modify($user['uid'], $role, $info, $baseInfo, $ex)) {
                $response->message = '修改失败'.$ex;
                goto err;
            }
        }
       
        
        success:
        $response->message = '修改成功';
        return json($response->getData());
        err:
        $response->code = 100;
        return json($response->getData());
    }

    /**
     * 用户消息
     *
     * @return json
     */
    public function myMsg()
    {
        $user = $this->user;
        $response = $this->response;
        $page = $this->param('page');
        $size = $this->param('size');
        $response->data = $this->model->getMsg($user['uid'], $page, $size);
        $response->_type = 'array';
        return json($response->getData());
    }

    /**
     * 删除消息
     *
     * @return json
     */
    public function delMsg()
    {
        $user = $this->user;
        $response = $this->response;
        $id = $this->param('id');
        if (false === $this->model->delMsg($id, $user['uid'], $msg)) {
            $response->code = 100;
            $response->message = $msg;
        }
        return json($response->getData());
    }

    
    // 用户信息消息通知
    public function hasNewMsg()
    {
        $response = $this->response;
        $uid  = $this->user['uid'];
        
        $base = $this->model->baseUser($uid);


        $data['has_new_msg'] = $base['has_new_msg'];

        $response->data = $data;
        return json($response->getData());
    }
}
